﻿using JinYuan.ControlLib;
using JinYuan.MES.Models;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using Language;
using Microsoft.Win32;
using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmSystemSet : MultiLanguageForm
    {
        private string devPath = string.Empty;
        private string PlcConfigFilePath = "plc_config.xlsx";
        private string FdConfigFilePath = "fd_config.xlsx";
        private List<PLCConfig> plcConfigs;
        private List<FDConfig> fdConfigs;
        private string PlcCommunicationConfigPath;
        private string variableConfigPath;

        private List<string> PLCTypes = new List<string>();       
        private List<string> NGLDTypes1 = new List<string>();//NG拉带类型
        private List<string> NGLDTypes2 = new List<string>();//NG拉带类型
        private List<string> NGLDTypes3 = new List<string>();//NG拉带类型
        private bool isEditing = false;
        private bool isFDEditing = false;
        private int editingRowIndex = -1;
        private int editingFDRowIndex = -1;
        private readonly string configFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");

        public FrmSystemSet(string devPath)
        {
            InitializeComponent();


            ////设置控件样式，去除缓冲
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.Selectable, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);


            PlcConfigFilePath = Path.Combine(configFolderPath, "Device.xlsx");
            FdConfigFilePath = Path.Combine(configFolderPath, "FdConfig.xlsx");
            PlcCommunicationConfigPath = Path.Combine(configFolderPath, "Group.xlsx");
            variableConfigPath = Path.Combine(configFolderPath, "Variable.xlsx");
            devPath = Path.Combine(configFolderPath, "Configure.ini");

            PLCTypes.AddRange(new string[] { "OmronFinsTCP", "OmronCipNet" });
            NGLDTypes1.AddRange(new string[] { "面1", "面2", "面3" });
            NGLDTypes2.AddRange(new string[] { "面1", "面2", "面3" });
            NGLDTypes3.AddRange(new string[] { "面1", "面2", "面3" });

            SetupDataGridView();
            SetupFDDataGridView();
            LoadPLCConfig();
           // LoadFDConfig();




            this.tog_AutoStart.IsChecked = CommonMethods.sysConfig.AutoStart;
            this.tog_AutoLogin.IsChecked = CommonMethods.sysConfig.AutoLogin;
            this.tog_AutoLock.IsChecked = CommonMethods.sysConfig.AutoLock;
            this.up_LockPeriod.CurrentValue = CommonMethods.sysConfig.LockPeriod;
            this.tog_AutoQieHuanM.IsChecked = CommonMethods.sysConfig.AutoQieHuanM;
            this.up_QieHuanPeriod.CurrentValue = CommonMethods.sysConfig.QieHuanMPeriod;
            this.up_ShowSeriesCount.CurrentValue = CommonMethods.sysConfig.ShowSeriesCount;


            this.tog_IsDebugMode.IsChecked = CommonMethods.sysConfig.IsDebugMode;
            this.tog_SwipeCardMode.IsChecked = CommonMethods.sysConfig.SwipeCardMode;
            this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching;
            this.tog_GetMesParam.IsChecked = CommonMethods.sysConfig.GetMesParam;
            this.tog_SaveThreadTime.IsChecked = CommonMethods.sysConfig.SaveThreadTime;

            this.tog_AutoStart.CheckedChanged += new System.EventHandler(this.tog_AutoStart_CheckedChanged);
            this.tog_AutoLogin.CheckedChanged += new System.EventHandler(this.tog_AutoLogin_CheckedChanged);
            this.tog_AutoLock.CheckedChanged += new System.EventHandler(this.tog_AutoLock_CheckedChanged);
            this.up_LockPeriod.ValueChanged += new System.EventHandler(this.up_LockPeriod_ValueChanged);

            this.tog_AutoQieHuanM.CheckedChanged += new System.EventHandler(this.tog_AutoQieHuanM_CheckedChanged);
            this.up_QieHuanPeriod.ValueChanged += new System.EventHandler(this.up_QieHuanPeriod_ValueChanged);

            this.up_ShowSeriesCount.ValueChanged += new System.EventHandler(this.up_ShowSeriesCount_ValueChanged);

            this.devPath = devPath;



            this.txtFactory_code.Text = CommonMethods.mesConfig.siteCode;
            this.txtline_No.Text = CommonMethods.mesConfig.lineCode;
            this.txtEqp_code.Text = CommonMethods.mesConfig.equipNum;

            this.txtEmployeeAuthCheck.Text = CommonMethods.mesConfig.EmployeeAuthCheck;
            this.txtMaterialInputInfo.Text = CommonMethods.mesConfig.MaterialInputInfo;
            this.txtDeviceParamRequest.Text = CommonMethods.mesConfig.DeviceParamRequest;

            this.txtDeviceParamChange.Text = CommonMethods.mesConfig.DeviceParamChange;
            this.txtProductInStation.Text = CommonMethods.mesConfig.ProductInStation;
            this.txtProductProcessParams.Text = CommonMethods.mesConfig.ProductProcessParams;

            this.txtProductResultParams.Text = CommonMethods.mesConfig.ProductResultParams;
            this.txtProductOutStation.Text = CommonMethods.mesConfig.ProductOutStation;
            this.txtDeviceAlarm.Text = CommonMethods.mesConfig.DeviceAlarm;

            this.txtDeviceStatus.Text = CommonMethods.mesConfig.DeviceStatus;
            this.txtEnergyConsumption.Text = CommonMethods.mesConfig.EnergyConsumption;
            this.txtAnemometer.Text = CommonMethods.mesConfig.Anemometer;

        }


        /// <summary>
        /// 初始化DataGrid
        /// </summary>
        private void SetupDataGridView()
        {
            // 设置基本属性
            dgvPlcConfigs.AutoGenerateColumns = false;
            dgvPlcConfigs.MultiSelect = false;

            // 添加数据列
            dgvPlcConfigs.Columns.AddRange(new DataGridViewColumn[]
            {
        new DataGridViewTextBoxColumn
        {
            Name = "PlcNum",
            HeaderText = "PLC编号",
            DataPropertyName = "PlcNum",
            ReadOnly = true,
            Width = 80,
            ValueType = typeof(int)
        },
        new DataGridViewComboBoxColumn
        {
            Name = "PLCType",
            HeaderText = "PLC类型",
            DataPropertyName = "PLCType",
            DataSource = new List<string>(PLCTypes), // 使用新列表避免引用问题
            Width = 160,
            ValueType = typeof(string),
             FlatStyle = FlatStyle.Flat,
            DefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = Color.FromArgb(14, 23, 38),  // 深色背景
                ForeColor = Color.White,                  // 白色文字
                SelectionBackColor = Color.FromArgb(0, 122, 204),  // 选中时的背景色
                SelectionForeColor = Color.White,         // 选中时的文字颜色
                Font = new Font("微软雅黑", 9F)           // 字体设置
            }
        },
        new DataGridViewTextBoxColumn
        {
            Name = "IPAddress",
            HeaderText = "IP地址",
            DataPropertyName = "IPAddress",
            Width = 120,
            ValueType = typeof(string)
        },
        new DataGridViewTextBoxColumn
        {
            Name = "Port",
            HeaderText = "端口号",
            DataPropertyName = "Port",
            Width = 80,
            ValueType = typeof(string)
        },
        new DataGridViewTextBoxColumn
        {
            Name = "HeartBeat",
            HeaderText = "心跳地址",
            DataPropertyName = "HeartBeat",
            Width = 100,
            ValueType = typeof(string)
        },
        new DataGridViewCheckBoxColumn
        {
            Name = "IsHeartBeat",
            HeaderText = "心跳状态",
            DataPropertyName = "IsHeartBeat",
            Width = 80,
            ValueType = typeof(bool),
            TrueValue = true,
            FalseValue = false
        },
        new DataGridViewCheckBoxColumn
        {
            Name = "IsActive",
            HeaderText = "激活状态",
            DataPropertyName = "IsActive",
            Width = 80,
            ValueType = typeof(bool),
            TrueValue = true,
            FalseValue = false
        },
        new DataGridViewTextBoxColumn
        {
            Name = "Remark",
            HeaderText = "备注",
            DataPropertyName = "Remark",
            Width = 150,
            ValueType = typeof(string)
        },
        new DataGridViewButtonColumn
        {
            Name = "Edit",
            HeaderText = "操作",
            Text = "修改".Translated(),
            UseColumnTextForButtonValue = true,
            Width = 80
        },

        new DataGridViewButtonColumn
        {
            Name = "Delete",
            HeaderText = "",
            Text = "删除".Translated(),
            UseColumnTextForButtonValue = true,
            Width = 80
        },
         new DataGridViewButtonColumn
        {
            Name = "CommConfig",
            HeaderText = "设置",
            Text = "通信组".Translated(),
            UseColumnTextForButtonValue = true,
            Width = 80
        },
          new DataGridViewButtonColumn
        {
            Name = "VariableConfig",
            HeaderText = "",
            Text = "变量".Translated(),
            UseColumnTextForButtonValue = true,
            Width = 80
        },
            });


            // 设置列为只读
            SetColumnsReadOnly(false);

            // 绑定事件
            dgvPlcConfigs.CellClick += DgvPlcConfigs_CellClick;
            dgvPlcConfigs.CellValidating += DgvPlcConfigs_CellValidating;
            dgvPlcConfigs.CellValueChanged += DgvPlcConfigs_CellValueChanged;
            dgvPlcConfigs.DataError += DgvPlcConfigs_DataError;

            // 设置自动调整行高
            dgvPlcConfigs.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dgvPlcConfigs.RowHeadersVisible = false;
        }


        private void SetColumnsReadOnly(bool readOnly)
        {
            foreach (DataGridViewColumn col in dgvPlcConfigs.Columns)
            {
                // PlcNum 列始终保持只读
                if (col.Name == "PlcNum")
                {
                    col.ReadOnly = true;
                    continue;
                }

                // 按钮列不需要设置 ReadOnly 属性
                if (col is DataGridViewButtonColumn)
                    continue;

                // 其他列根据参数设置
                col.ReadOnly = readOnly;
            }
        }
        private void SetColumnsFDReadOnly(bool readOnly)
        {
            foreach (DataGridViewColumn col in dgvFdConfigs.Columns)
            {
                // PlcNum 列始终保持只读
                if (col.Name == "FdNum")
                {
                    col.ReadOnly = true;
                    continue;
                }

                // 按钮列不需要设置 ReadOnly 属性
                if (col is DataGridViewButtonColumn)
                    continue;

                // 其他列根据参数设置
                col.ReadOnly = readOnly;
            }
        }

        /// <summary>
        /// 初始化分档DataGrid
        /// </summary>
        private void SetupFDDataGridView()
        {
            // 设置基本属性
            dgvFdConfigs.AutoGenerateColumns = false;
            dgvFdConfigs.MultiSelect = false;

            // 添加数据列
            dgvFdConfigs.Columns.AddRange(new DataGridViewColumn[]
            {
        new DataGridViewTextBoxColumn
        {
            Name = "FdNum",
            HeaderText = "分档编号",
            DataPropertyName = "FdNum",
            ReadOnly = true,
            Width = 80,
            ValueType = typeof(int)
        },
        #region 分档类型
        new DataGridViewTextBoxColumn
        {
            Name = "OKLD1Type",
            HeaderText = "OK拉带类型1",
            DataPropertyName = "OKLD1Type",
            Width = 120,
            ValueType = typeof(string)
        },
        new DataGridViewTextBoxColumn
        {
            Name = "OKLD2Type",
            HeaderText = "OK拉带类型2",
            DataPropertyName = "OKLD2Type",
            Width = 120,
            ValueType = typeof(string)
        },
        new DataGridViewTextBoxColumn
        {
            Name = "OKLD3Type",
            HeaderText = "OK拉带类型3",
            DataPropertyName = "OKLD3Type",
            Width = 120,
            ValueType = typeof(string)
        },
        new DataGridViewTextBoxColumn
        {
            Name = "OKLD4Type",
            HeaderText = "OK拉带类型4",
            DataPropertyName = "OKLD4Type",
            Width = 120,
            ValueType = typeof(string)
        },
        #endregion
        #region NG拉带类型
         new DataGridViewComboBoxColumn
        {
            Name = "NGLD5Type",
            HeaderText = "NG拉带类型5",
            DataPropertyName = "NGLD5Type",//NG拉带
            DataSource = new List<string>(NGLDTypes1), // 使用新列表避免引用问题
            Width = 160,
            ValueType = typeof(string),
            FlatStyle = FlatStyle.Flat,
            DefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = Color.FromArgb(14, 23, 38),  // 深色背景
                ForeColor = Color.White,                  // 白色文字
                SelectionBackColor = Color.FromArgb(0, 122, 204),  // 选中时的背景色
                SelectionForeColor = Color.White,         // 选中时的文字颜色
                Font = new Font("微软雅黑", 9F)           // 字体设置
            }
        },
        new DataGridViewComboBoxColumn
        {
            Name = "NGLD6Type",
            HeaderText = "NG拉带类型6",
            DataPropertyName = "NGLD6Type",//NG拉带
            DataSource = new List<string>(NGLDTypes2), // 使用新列表避免引用问题
            Width = 160,
            ValueType = typeof(string),
                FlatStyle = FlatStyle.Flat,
            DefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = Color.FromArgb(14, 23, 38),  // 深色背景
                ForeColor = Color.White,                  // 白色文字
                SelectionBackColor = Color.FromArgb(0, 122, 204),  // 选中时的背景色
                SelectionForeColor = Color.White,         // 选中时的文字颜色
                Font = new Font("微软雅黑", 9F)           // 字体设置
            }
        },
        new DataGridViewComboBoxColumn
        {
            Name = "NGLD7Type",
            HeaderText = "NG拉带类型7",
            DataPropertyName = "NGLD7Type",//NG拉带
            DataSource = new List<string>(NGLDTypes3), // 使用新列表避免引用问题
            Width = 160,
            ValueType = typeof(string),
                FlatStyle = FlatStyle.Flat,
            DefaultCellStyle = new DataGridViewCellStyle
            {
                BackColor = Color.FromArgb(14, 23, 38),  // 深色背景
                ForeColor = Color.White,                  // 白色文字
                SelectionBackColor = Color.FromArgb(0, 122, 204),  // 选中时的背景色
                SelectionForeColor = Color.White,         // 选中时的文字颜色
                Font = new Font("微软雅黑", 9F)           // 字体设置
            }
        },
        #endregion
        #region 开启分档
         new DataGridViewCheckBoxColumn
        {
            Name = "IsFDActive",
            HeaderText = "开启分档",
            DataPropertyName = "IsFDActive",
            Width = 80,
            ValueType = typeof(bool),
            TrueValue = true,
            FalseValue = false
        },
          new DataGridViewCheckBoxColumn
        {
            Name = "IsNGActive",
            HeaderText = "NG电池不分类排出",
            DataPropertyName = "IsNGActive",
            Width = 80,
            ValueType = typeof(bool),
            TrueValue = true,
            FalseValue = false
        },
        #endregion

        new DataGridViewButtonColumn
        {
            Name = "Edit",
            HeaderText = "操作",
            Text = "修改".Translated(),
            UseColumnTextForButtonValue = true,
            Width = 80
        }


            });


            // 设置列为只读
            SetColumnsFDReadOnly(false);

            // 绑定事件
            dgvFdConfigs.CellClick += DgvFdConfigs_CellClick;
            dgvFdConfigs.CellValidating += DgvFdConfigs_CellValidating;
            dgvFdConfigs.CellValueChanged += DgvFdConfigs_CellValueChanged;
            dgvFdConfigs.DataError += DgvFdConfigs_DataError;

            // 设置自动调整行高
            dgvFdConfigs.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            dgvFdConfigs.RowHeadersVisible = false;
        }
        /// <summary>
        /// 加载PLCConfig配置文件
        /// </summary>
        private void LoadPLCConfig()
        {

            try
            {
                if (File.Exists(PlcConfigFilePath))
                {
                    using (var stream = File.OpenRead(PlcConfigFilePath))
                    {
                        var devices = MiniExcel.Query<PLCConfig>(stream).ToList();
                        plcConfigs = devices.Select(device => new PLCConfig
                        {
                            PlcNum = device.PlcNum,
                            PLCType = device.PLCType,
                            IPAddress = device.IPAddress,
                            Port = device.Port.ToString(),
                            HeartBeat = device.HeartBeat,
                            IsHeartBeat = device.IsHeartBeat,
                            IsActive = device.IsActive,
                            Remark = device.Remark,
                        }).ToList();
                    }

                }
                else
                {
                    plcConfigs = new List<PLCConfig>();
                }

                RefreshDataGridView();
               // RefreshFDDataGridView();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置文件失败：{ex.Message}", "错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
                plcConfigs = new List<PLCConfig>();
            }


        }
        private void LoadFDConfig()
        {

            try
            {
                if (File.Exists(FdConfigFilePath))
                {
                    using (var stream = File.OpenRead(FdConfigFilePath))
                    {
                        var devices = MiniExcel.Query<FDConfig>(stream).ToList();
                        fdConfigs = devices.Select(device => new FDConfig
                        {
                            FdNum = device.FdNum,
                            OKLD1Type = device.OKLD1Type,
                            OKLD2Type = device.OKLD2Type,
                            OKLD3Type = device.OKLD3Type,
                            OKLD4Type = device.OKLD4Type,
                            NGLD5Type = device.NGLD5Type,
                            NGLD6Type = device.NGLD6Type,
                            NGLD7Type = device.NGLD7Type,
                            IsFDActive = device.IsFDActive,
                            IsNGActive = device.IsNGActive
                        }).ToList();
                    }

                }
                else
                {
                    fdConfigs = new List<FDConfig>();
                }

                RefreshFDDataGridView();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置文件失败：{ex.Message}", "错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
                fdConfigs = new List<FDConfig>();
            }


        }

        private void DgvPlcConfigs_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var columnName = dgvPlcConfigs.Columns[e.ColumnIndex].Name;

            // 如果正在编辑其他行，阻止操作
            if (isEditing && editingRowIndex != e.RowIndex)
            {
                MessageBox.Show("请先完成当前编辑操作", "提示",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var plcConfig = plcConfigs[e.RowIndex];

            switch (columnName)
            {
                case "Edit":
                    HandleEdit(e.RowIndex);
                    break;
                case "CommConfig":
                    HandleCommConfig(plcConfig);
                    break;
                case "VariableConfig":
                    HandleVariableConfig(plcConfig);
                    break;
                case "Delete":
                    HandleDelete(e.RowIndex, plcConfig);
                    break;
            }
        }

        private void DgvFdConfigs_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var columnName = dgvFdConfigs.Columns[e.ColumnIndex].Name;

            // 如果正在编辑其他行，阻止操作
            if (isFDEditing && editingFDRowIndex != e.RowIndex)
            {
                MessageBox.Show("请先完成当前编辑操作", "提示",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var fdConfig = fdConfigs[e.RowIndex];

            switch (columnName)
            {
                case "Edit":
                    HandleFDEdit(e.RowIndex);
                    break;
                case "CommConfig":
                    HandleCommFdConfig(fdConfig);
                    break;
                case "VariableConfig":
                    HandleVariableFdConfig(fdConfig);
                    break;
                case "Delete":
                    HandleFdDelete(e.RowIndex, fdConfig);
                    break;
            }
        }
        // 相应地，在处理编辑状态时，也需要修改 HandleEdit 方法
        private void HandleEdit(int rowIndex)
        {
            if (!isEditing)
            {
                // 开始编辑
                isEditing = true;
                editingRowIndex = rowIndex;
                SetColumnsReadOnly(false);  // 设置其他列为可编辑

                // 更改编辑按钮文本为"保存"
                dgvPlcConfigs.Rows[rowIndex].Cells["Edit"].Value = "保存";

                // 禁用其他行的按钮
                foreach (DataGridViewRow row in dgvPlcConfigs.Rows)
                {
                    if (row.Index != rowIndex)
                    {
                        if (row.Cells["Edit"] is DataGridViewButtonCell editCell)
                            editCell.Value = "";
                        if (row.Cells["CommConfig"] is DataGridViewButtonCell configCell)
                            configCell.Value = "";
                        if (row.Cells["Delete"] is DataGridViewButtonCell deleteCell)
                            deleteCell.Value = "";
                    }
                }

                // 禁用添加按钮
                btAddPLC.Enabled = false;
            }
            else if (rowIndex == editingRowIndex)
            {
                // 保存更改
                if (ValidateRow(rowIndex))
                {
                    SaveChanges(rowIndex);
                    EndEditing();
                }
            }
        }

        private void HandleFDEdit(int rowIndex)
        {
            if (!isFDEditing)
            {
                // 开始编辑
                isFDEditing = true;
                editingFDRowIndex = rowIndex;
                SetColumnsFDReadOnly(false);  // 设置其他列为可编辑

                // 更改编辑按钮文本为"保存"
                dgvFdConfigs.Rows[rowIndex].Cells["Edit"].Value = "保存";

                // 禁用其他行的按钮
                foreach (DataGridViewRow row in dgvFdConfigs.Rows)
                {
                    if (row.Index != rowIndex)
                    {
                        if (row.Cells["Edit"] is DataGridViewButtonCell editCell)
                            editCell.Value = "";
                        if (row.Cells["CommConfig"] is DataGridViewButtonCell configCell)
                            configCell.Value = "";
                        if (row.Cells["Delete"] is DataGridViewButtonCell deleteCell)
                            deleteCell.Value = "";
                    }
                }

                // 禁用添加按钮
                //btAddPLC.Enabled = false;
                RefreshFDDataGridView();
            }
            else if (rowIndex == editingFDRowIndex)
            {
                // 保存更改
                //if (ValidateRow(rowIndex))
                {
                    SaveFDChanges(rowIndex);
                    EndFDEditing();
                }
            }
        }

        private void EndEditing()
        {
            isEditing = false;
            editingRowIndex = -1;
            SetColumnsReadOnly(true);

            // 恢复所有按钮文本和状态
            foreach (DataGridViewRow row in dgvPlcConfigs.Rows)
            {
                row.Cells["Edit"].Value = "编辑";
                row.Cells["CommConfig"].Value = "通信组";
                row.Cells["Delete"].Value = "删除";
            }

            // 启用添加按钮
            btAddPLC.Enabled = true;
        }
        private void EndFDEditing()
        {
            isFDEditing = false;
            editingFDRowIndex = -1;
            SetColumnsFDReadOnly(true);

            // 恢复所有按钮文本和状态
            foreach (DataGridViewRow row in dgvFdConfigs.Rows)
            {
               // row.Cells["Edit"].Value = "编辑";
               // row.Cells["CommConfig"].Value = "通信组";
               // row.Cells["Delete"].Value = "删除";
            }

            // 启用添加按钮
            btAddPLC.Enabled = true;
        }


        private void HandleCommConfig(PLCConfig config)
        {
            using (var commForm = new CommunicationEditForm(config.PlcNum))
            {
                if (commForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果需要刷新主窗体数据
                    RefreshDataGridView();
                }
            }
        }
        private void HandleCommFdConfig(FDConfig fdconfig)
        {
            //using (var commForm = new CommunicationEditForm(fdconfig.FdNum))
            //{
            //    if (commForm.ShowDialog() == DialogResult.OK)
            //    {
            //        // 如果需要刷新主窗体数据
            //        RefreshFDDataGridView();
            //    }
            //}
        }

        private void HandleVariableConfig(PLCConfig config)
        {
            using (var commForm = new VariableEditForm(config.PlcNum))
            {
                if (commForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果需要刷新主窗体数据
                    RefreshDataGridView();
                }
            }
        }
        private void HandleVariableFdConfig(FDConfig fdconfig)
        {
            //using (var commForm = new VariableEditForm(fdconfig.FdNum))
            //{
            //    if (commForm.ShowDialog() == DialogResult.OK)
            //    {
            //        // 如果需要刷新主窗体数据
            //        RefreshFDDataGridView();
            //    }
            //}
        }

        private void HandleDelete(int rowIndex, PLCConfig config)
        {
            if (MessageBox.Show($"确定要删除 PLC {config.PlcNum} 吗？", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                plcConfigs.RemoveAt(rowIndex);
                SavePLCConfig();
                RefreshDataGridView();
            }
        }
        private void HandleFdDelete(int rowIndex, FDConfig fdconfig)
        {
            if (MessageBox.Show($"确定要删除 分档 {fdconfig.FdNum} 吗？", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                fdConfigs.RemoveAt(rowIndex);
                SaveFDConfig();
                RefreshFDDataGridView();
            }
        }


        private bool ValidateRow(int rowIndex)
        {
            var row = dgvPlcConfigs.Rows[rowIndex];

            // IP地址验证
            string ipAddress = row.Cells["IPAddress"].Value?.ToString();
            if (!IsValidIPAddress(ipAddress))
            {
                MessageBox.Show("请输入有效的IP地址", "验证错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // 端口验证
            string port = row.Cells["Port"].Value?.ToString();
            if (!IsValidPort(port))
            {
                MessageBox.Show("端口号必须在0-65535之间", "验证错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            // PLC类型验证
            string plcType = row.Cells["PLCType"].Value?.ToString();
            if (string.IsNullOrWhiteSpace(plcType))
            {
                MessageBox.Show("请选择PLC类型", "验证错误",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }


        private void SaveChanges(int rowIndex)
        {
            try
            {
                var row = dgvPlcConfigs.Rows[rowIndex];
                var config = plcConfigs[rowIndex];

                // 更新配置对象
                config.PLCType = row.Cells["PLCType"].Value?.ToString() ?? "";
                config.IPAddress = row.Cells["IPAddress"].Value?.ToString() ?? "";
                config.Port = row.Cells["Port"].Value?.ToString() ?? "";
                config.HeartBeat = row.Cells["HeartBeat"].Value?.ToString() ?? "";
                config.IsHeartBeat = row.Cells["IsHeartBeat"].Value != null &&
                                    Convert.ToBoolean(row.Cells["IsHeartBeat"].Value);
                config.IsActive = row.Cells["IsActive"].Value != null &&
                                 Convert.ToBoolean(row.Cells["IsActive"].Value);
                config.Remark = row.Cells["Remark"].Value?.ToString() ?? "";

                // 保存更改
                SavePLCConfig();
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // 这里只显示错误信息，不再抛出异常
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void SaveFDChanges(int rowIndex)
        {
            try
            {
                var row = dgvFdConfigs.Rows[rowIndex];
                var config = fdConfigs[rowIndex];

                // 更新配置对象
                config.OKLD1Type = row.Cells["OKLD1Type"].Value?.ToString() ?? "";
                config.OKLD2Type = row.Cells["OKLD2Type"].Value?.ToString() ?? "";
                config.OKLD3Type = row.Cells["OKLD3Type"].Value?.ToString() ?? "";
                config.OKLD4Type = row.Cells["OKLD4Type"].Value?.ToString() ?? "";
                config.NGLD5Type = row.Cells["NGLD5Type"].Value?.ToString() ?? "";
                config.NGLD6Type = row.Cells["NGLD6Type"].Value?.ToString() ?? "";
                config.NGLD7Type = row.Cells["NGLD7Type"].Value?.ToString() ?? "";

                config.IsFDActive = row.Cells["IsFDActive"].Value != null &&
                                    Convert.ToBoolean(row.Cells["IsFDActive"].Value);
                config.IsNGActive = row.Cells["IsNGActive"].Value != null &&
                                 Convert.ToBoolean(row.Cells["IsNGActive"].Value);

                // 保存更改
                SaveFDConfig();
                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // 这里只显示错误信息，不再抛出异常
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        private void DgvPlcConfigs_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.RowIndex < 0 || !isEditing || e.RowIndex != editingRowIndex) return;

            string newValue = e.FormattedValue.ToString();
            var column = dgvPlcConfigs.Columns[e.ColumnIndex];

            switch (column.Name)
            {
                case "IPAddress":
                    if (!IsValidIPAddress(newValue))
                    {
                        e.Cancel = true;
                        dgvPlcConfigs.Rows[e.RowIndex].ErrorText = "请输入有效的IP地址";
                    }
                    break;

                case "Port":
                    if (!IsValidPort(newValue))
                    {
                        e.Cancel = true;
                        dgvPlcConfigs.Rows[e.RowIndex].ErrorText = "请输入有效的端口号（0-65535）";
                    }
                    break;
            }
        }
        private void DgvFdConfigs_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.RowIndex < 0 || !isFDEditing || e.RowIndex != editingFDRowIndex) return;

            string newValue = e.FormattedValue.ToString();
            var column = dgvFdConfigs.Columns[e.ColumnIndex];
           
        }

        private void DgvPlcConfigs_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            dgvPlcConfigs.Rows[e.RowIndex].ErrorText = string.Empty;
        }
        private void DgvFdConfigs_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            dgvFdConfigs.Rows[e.RowIndex].ErrorText = string.Empty;
        }

        private void DgvPlcConfigs_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
            string columnName = dgvPlcConfigs.Columns[e.ColumnIndex].HeaderText;
            MessageBox.Show($"'{columnName}'列的输入数据格式不正确", "数据错误",
                          MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        private void DgvFdConfigs_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
            string columnName = dgvFdConfigs.Columns[e.ColumnIndex].HeaderText;
            MessageBox.Show($"'{columnName}'列的输入数据格式不正确", "数据错误",
                          MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        /// <summary>
        /// 验证IP地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private bool IsValidIPAddress(string ip)
        {
            if (string.IsNullOrWhiteSpace(ip))
                return false;

            try
            {
                // 分割IP地址
                string[] parts = ip.Split('.');
                if (parts.Length != 4)
                    return false;

                // 验证每个部分
                foreach (string part in parts)
                {
                    if (!int.TryParse(part, out int number))
                        return false;

                    if (number < 0 || number > 255)
                        return false;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        private bool IsValidPort(string port)
        {
            if (string.IsNullOrWhiteSpace(port))
                return false;

            return int.TryParse(port, out int portNum) && portNum >= 0 && portNum <= 65535;
        }

        private void SavePLCConfig()
        {
            try
            {
                // 创建备份
                if (File.Exists(PlcConfigFilePath))
                {
                    string backupFile = $"{PlcConfigFilePath}.bak";
                    File.Copy(PlcConfigFilePath, backupFile, true);
                }

                // 直接保存到目标文件
                MiniExcel.SaveAs(PlcConfigFilePath, plcConfigs, overwriteFile: true);
            }
            catch (IOException ex)
            {
                MessageBox.Show($"保存文件时发生IO错误：{ex.Message}\n请确保文件未被其他程序占用。",
                              "保存错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show($"没有足够的权限保存文件：{ex.Message}\n请确保有写入权限。",
                              "权限错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置时发生错误：{ex.Message}",
                              "保存错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }
        private void SaveFDConfig()
        {
            try
            {
                // 创建备份
                if (File.Exists(FdConfigFilePath))
                {
                    string backupFile = $"{FdConfigFilePath}.bak";
                    File.Copy(FdConfigFilePath, backupFile, true);
                }

                // 直接保存到目标文件
                MiniExcel.SaveAs(FdConfigFilePath, fdConfigs, overwriteFile: true);
            }
            catch (IOException ex)
            {
                MessageBox.Show($"保存文件时发生IO错误：{ex.Message}\n请确保文件未被其他程序占用。",
                              "保存错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show($"没有足够的权限保存文件：{ex.Message}\n请确保有写入权限。",
                              "权限错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置时发生错误：{ex.Message}",
                              "保存错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        private void RefreshDataGridView()
        {
            dgvPlcConfigs.DataSource = null;
            dgvPlcConfigs.DataSource = new BindingList<PLCConfig>(plcConfigs);
        }
        private void RefreshFDDataGridView()
        {
            dgvFdConfigs.DataSource = null;
            dgvFdConfigs.DataSource = new BindingList<FDConfig>(fdConfigs);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            if (isEditing)
            {
                var result = MessageBox.Show("当前有未保存的更改，是否保存？", "保存确认",
                    MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Question);

                switch (result)
                {
                    case DialogResult.Yes:
                        if (ValidateRow(editingRowIndex))
                        {
                            SaveChanges(editingRowIndex);
                            EndEditing();
                            EndFDEditing();
                        }
                        else
                        {
                            e.Cancel = true;
                        }
                        break;
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                        // DialogResult.No 直接关闭
                }
            }
        }

        /// <summary>
        /// 添加PLC
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddPLC_Click(object sender, EventArgs e)
        {
            if (isEditing)
            {
                MessageBox.Show("请先完成当前编辑操作", "提示",
                              MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var maxPlcNum = plcConfigs.Count > 0 ? plcConfigs.Max(p => p.PlcNum) : 0;

            var newConfig = new PLCConfig
            {
                PlcNum = maxPlcNum + 1,
                PLCType = "",
                IPAddress = "",
                Port = "",
                HeartBeat = "",
                IsHeartBeat = false,
                IsActive = false,
                Remark = ""
            };

            plcConfigs.Add(newConfig);
            RefreshDataGridView();

            // 自动开始编辑新行
            int newRowIndex = dgvPlcConfigs.Rows.Count - 1;
            HandleEdit(newRowIndex);
        }


        private void BtnSaveAll_Click(object sender, EventArgs e)
        {
            try
            {
                SavePLCConfig();
                MessageBox.Show("所有配置已保存", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


        #region 系统相关配置
        private void tog_AutoLogin_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveAutoLogin(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改软件自动登录方式".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        private void tog_AutoStart_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveAutoStart(((Toggle)sender).IsChecked))
            {
                //写入注册表
                AutoStart(((Toggle)sender).IsChecked);
                CommonMethods.AddOPLog(false, "修改软件自动启动方式".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        private void tog_AutoLock_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveAutoLock(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改无操作自动锁屏方式".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        private void up_LockPeriod_ValueChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveLockPeriod(Convert.ToInt32(((UpDownLabel)sender).CurrentValue)))
            {
                CommonMethods.AddOPLog(false, "修改锁屏间隔时间".Translated() + "：" + ((UpDownLabel)sender).CurrentValue.ToString());
                CommonMethods.GetSysConfig();
            }
        }


        private void tog_AutoQieHuanM_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveAutoQieHuanM(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改无操作自动切换监控界面方式".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        private void tog_IsDebugMod_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveIsDebug(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改调试模式".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }



        private void up_QieHuanPeriod_ValueChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveQieHuanMPeriod(Convert.ToInt32(((UpDownLabel)sender).CurrentValue)))
            {
                CommonMethods.AddOPLog(false, "修改切换监控界面间隔时间".Translated() + "：" + ((UpDownLabel)sender).CurrentValue.ToString());
                CommonMethods.GetSysConfig();
            }
        }


        private void up_ShowSeriesCount_ValueChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveShowSeriesCount(Convert.ToInt32(((UpDownLabel)sender).CurrentValue)))
            {
                CommonMethods.AddOPLog(false, "修改曲线显示数量".Translated() + "：" + ((UpDownLabel)sender).CurrentValue.ToString());
                CommonMethods.GetSysConfig();
            }
        }


        private void tog_SwipeCardMode_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveSwipeCardMode(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改刷卡模式".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
                if (CommonMethods.sysConfig.SwipeCardMode && CommonMethods.IsLoginOk)
                {
                    DialogResult dialogResult1 = new FrmMsgBoxWithAck("当前已登录".Translated() + "，" + "是否切换刷卡模式".Translated(), "提示".Translated()).ShowDialog();
                    if (dialogResult1 == DialogResult.OK)
                    {
                        CommonMethods.AddOPLog(false, $"切换刷卡模式成功".Translated() + "，" + "当前用户已注销".Translated());
                        CommonMethods.IsLoginOk = false;
                        CommonMethods.sysConfig.SwipeCardMode = true;
                        this.tog_SwipeCardMode.IsChecked = CommonMethods.sysConfig.SwipeCardMode;
                        CommonMethods.SaveSwipeCardMode(((Toggle)sender).IsChecked);
                        CommonMethods.GetSysConfig();
                        //切屏
                        CommonMethods.sysConfig.ScreenCutting = true;
                    }
                    else
                    {
                        CommonMethods.IsLoginOk = true;
                        CommonMethods.sysConfig.SwipeCardMode = false;
                        this.tog_SwipeCardMode.IsChecked = CommonMethods.sysConfig.SwipeCardMode;
                        CommonMethods.SaveSwipeCardMode(((Toggle)sender).IsChecked);
                        CommonMethods.GetSysConfig();
                    }
                }
            }
        }


        private void tog_OpenMesModel_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.plcDevices[0].IsConnected && CommonMethods.sysConfig.MesModeSwitching)
            {
                CommonMethods.sysConfig.MesModeSwitching = true;
                this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching;
                CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked);
                CommonMethods.GetSysConfig();
                new FrmMsgBoxOutWithAck(2, "先停止运行再切换MES".Translated(), "提示".Translated()).ShowDialog();
                return;
            }
            if (CommonMethods.plcDevices[0].IsConnected && !CommonMethods.sysConfig.MesModeSwitching)
            {
                CommonMethods.sysConfig.MesModeSwitching = false;
                this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching;
                CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked);
                CommonMethods.GetSysConfig();
                new FrmMsgBoxOutWithAck(2, "先停止运行再切换MES".Translated(), "提示".Translated()).ShowDialog();
                return;
            }
            if (CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改MES/非MES模式切换".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
                if (CommonMethods.sysConfig.MesModeSwitching)
                {
                    FrmLoginMes frmLoginMes = new FrmLoginMes();
                    if (frmLoginMes.ShowDialog() != DialogResult.OK)
                    {
                        CommonMethods.sysConfig.MesModeSwitching = false;
                        this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching;
                        CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked);
                        CommonMethods.GetSysConfig();
                    }
                }
                else
                {
                    DialogResult dialogResult = new FrmMsgBoxWithAck("是否关闭MES模式".Translated(), "提示".Translated()).ShowDialog();
                    if (dialogResult == DialogResult.OK)
                    {
                        CommonMethods.AddOPLog(false, "关闭MES模式成功".Translated() + "，" + "MES用户已注销".Translated());
                        CommonMethods.sysConfig.MesModeSwitching = false;
                        this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching;
                        CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked);
                        CommonMethods.GetSysConfig();
                    }
                    else
                    {
                        CommonMethods.sysConfig.MesModeSwitching = true;
                        this.tog_OpenMesModel.IsChecked = CommonMethods.sysConfig.MesModeSwitching;
                        CommonMethods.SaveOpenMesModel(((Toggle)sender).IsChecked);
                        CommonMethods.GetSysConfig();
                    }
                }
            }
        }

        private void tog_GetMesParam_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveGetMesParam(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改获取MES参数".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }

        private void tog_SaveThreadTime_CheckedChanged(object sender, EventArgs e)
        {
            if (CommonMethods.SaveSaveThreadTime(((Toggle)sender).IsChecked))
            {
                CommonMethods.AddOPLog(false, "修改线程耗时日志保存".Translated() + "：" + ((Toggle)sender).IsChecked.ToString());
                CommonMethods.GetSysConfig();
            }
        }
        /// <summary>
        /// 修改程序在注册表的 键值
        /// </summary>
        /// <param name="isAuto"></param>
        private void AutoStart(bool isAuto = true)
        {
            if (isAuto == true)
            {
                RegistryKey R_local = Registry.CurrentUser;
                RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run");
                R_run.SetValue("KYJPro", System.Windows.Forms.Application.ExecutablePath);
                R_run.Close();
                R_local.Close();
            }
            else
            {
                RegistryKey R_local = Registry.CurrentUser;
                RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\windows\CurrentVersion\Run");
                R_run.DeleteSubKey("KYJPro", false);
                R_run.Close();
                R_local.Close();
            }
        }

        #endregion

        private void btn_Sure_Click(object sender, EventArgs e)
        {

            CommonMethods.Configxml["MES_CONFIG"]["SiteCode"] = this.txtFactory_code.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["LineCode"] = this.txtline_No.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["EquipNum"] = this.txtEqp_code.Text.Trim();

            CommonMethods.Configxml["MES_CONFIG"]["EmployeeAuthCheck"] = this.txtEmployeeAuthCheck.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["MaterialInputInfo"] = this.txtMaterialInputInfo.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["DeviceParamRequest"] = this.txtDeviceParamRequest.Text.Trim();

            CommonMethods.Configxml["MES_CONFIG"]["DeviceParamChange"] = this.txtDeviceParamChange.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["ProductInStation"] = this.txtProductInStation.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["ProductProcessParams"] = this.txtProductProcessParams.Text.Trim();

            CommonMethods.Configxml["MES_CONFIG"]["ProductResultParams"] = this.txtProductResultParams.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["ProductOutStation"] = this.txtProductOutStation.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["DeviceAlarm"] = this.txtDeviceAlarm.Text.Trim();

            CommonMethods.Configxml["MES_CONFIG"]["DeviceStatus"] = this.txtDeviceStatus.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["EnergyConsumption"] = this.txtEnergyConsumption.Text.Trim();
            CommonMethods.Configxml["MES_CONFIG"]["Anemometer"] = this.txtAnemometer.Text.Trim();

            CommonMethods.WriteXmlFile(CommonMethods.Configxml, CommonMethods.xmlFilePath);

            CommonMethods.mesConfig = CommonMethods.GetMesConfig();

            DialogResult dialogResult = new FrmMsgBoxOutWithAck(1, "参数修改成功", "参数设置").ShowDialog();
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.txtFactory_code.Text = CommonMethods.mesConfig.siteCode;
            this.txtline_No.Text = CommonMethods.mesConfig.lineCode;
            this.txtEqp_code.Text = CommonMethods.mesConfig.equipNum;
        }

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }






        #endregion

        private void btnFdConfig_Click(object sender, EventArgs e)
        {
            this.dgvFdConfigs.Visible = true;
            this.dgvPlcConfigs.Visible = false;
        }

        private void btnPlcConfig_Click(object sender, EventArgs e)
        {
            this.dgvFdConfigs.Visible = false;
            this.dgvPlcConfigs.Visible = true;
        }
    }
}
